package com.ego.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ego.exception.EgoException;
import com.ego.exception.ExceptionEnum;
import com.ego.order.config.PayHelper;
import com.ego.order.mapper.OrderMapper;
import com.ego.order.mapper.PayLogMapper;
import com.ego.order.pojo.Order;
import com.ego.order.pojo.PayLog;
import com.ego.order.service.PayLogService;
import com.github.wxpay.sdk.WXPayConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * @author Ares
 * @date 2020-12-12
 */
@Service
@Slf4j
public class PayLogServiceImpl implements PayLogService {

    @Resource
    private PayLogMapper payLogMapper;
    @Resource
    private PayHelper payHelper;
    @Resource
    private OrderMapper orderMapper;
    @Override
    @Transactional
    public Integer queryOrderStateByOrderId(Long orderId) {
        //优先去支付日志表中查询信息
        PayLog payLog = payLogMapper.selectById(orderId);
        if (payLog == null || com.ego.order.enums.PayStateEnum.NOT_PAY.getValue() == payLog.getStatus()) {
            //未支付，调用微信接口查询订单支付状态
            return payHelper.queryPayState(orderId).getValue();
        }

        if (com.ego.order.enums.PayStateEnum.SUCCESS.getValue() == payLog.getStatus()) {
            //支付成功，返回1
            return com.ego.order.enums.PayStateEnum.SUCCESS.getValue();
        }

        //如果是其他状态，返回失败
        return com.ego.order.enums.PayStateEnum.FAIL.getValue();
    }

    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    @Override
    public void save(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        payLogMapper.insert(PayLog.builder()
                .orderId(orderId)
                .totalFee(order.getActualPay())
                .userId(order.getUserId())
                .status(1)
                .payType(order.getPaymentType())
                .createTime(order.getCreateTime())
                .build());
    }

    @Override
    public void handleNotify(Map<String, String> result) throws ParseException {
        //判断通信结果
        if(WXPayConstants.FAIL.equals(result.get("return_code"))){
            EgoException.error(log, ExceptionEnum.ORDER_STATUS_EXCEPTION);
        }
        //判断下单结果
        if(WXPayConstants.FAIL.equals(result.get("result_code"))){
            EgoException.error(log, ExceptionEnum.ORDER_STATUS_EXCEPTION);
        }

        //判断数据是否被篡改
        payHelper.isSignatureValid(result);

        Long orderId = Long.valueOf(result.get("out_trade_no"));
        String transaction_id = result.get("transaction_id");
        String time_end = result.get("time_end");
        SimpleDateFormat sldf = new SimpleDateFormat();
        PayLog payLog = payLogMapper.selectOne(new QueryWrapper<PayLog>().eq("order_id", orderId));
        if (payLog.getStatus() == com.ego.order.enums.PayStateEnum.NOT_PAY.getValue()) {
            payLogMapper.updateById(PayLog.builder()
                    .orderId(orderId)
                    .transactionId(transaction_id)
                    .payTime(sldf.parse(time_end))
                    .build());
        }
    }
}
